package com.qilin.hammer;
import java.util.*;

public class IterableClass<T> implements Iterable<T> {

	private Collection<T> data;
	private Object[] t;
	/**
	 * @param args
	 */
	
	public IterableClass(Collection<T> c){
		this.data=c;
		this.t = new Object[1];
	}
	
	public Iterator<T> iterator(){
		return new Iterator<T>() {
			int current = 0;
			public boolean hasNext(){ return current<data.size(); }
			@SuppressWarnings(value={"unchecked"})
			public T next(){ return (T)data.toArray()[current++]; }
			public void remove(){
				IterableClass.this.remove();
			}
		};
	}
	
	public Iterable<T> reverse(){
		return new Iterable<T>(){
			public Iterator<T> iterator(){
				return new Iterator<T>(){
					int current = data.size()-1;
					public boolean hasNext(){ return current>-1; }
					@SuppressWarnings(value={"unchecked"})
					public T next(){ return (T)data.toArray(t)[current--]; };
					public void remove(){
						IterableClass.this.remove();
					}
				};
			}
		};
	}
	
	public Iterable<T> random(){
		return new Iterable<T>(){
			public Iterator<T> iterator(){
				List<T> shuffled = new ArrayList<T>();
				for(T t:data)
					shuffled.add(t);
				Collections.shuffle(shuffled, new Random(12));
				return shuffled.iterator();
			}
		};
	}
	
	private void remove(){throw new UnsupportedOperationException();}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String info="my name is zhang run meng!"; 
		Integer numbers[] ={1,3,5,7,9,2,4,6,8,10}; 
		IterableClass<String> data = new IterableClass<String>(Arrays.asList(info.split(" "))); 
		for(String s:data)
			System.out.print(s+" ");
		System.out.println();
		for(String s:data.reverse())
			System.out.print(s+" ");
		System.out.println();
		for(String s:data.random())
			System.out.print(s+" ");
		System.out.println();
		IterableClass<Integer> data1 = new IterableClass<Integer>(Arrays.asList(numbers)); 
		for(int s:data1)
			System.out.print(s+" ");
		System.out.println();
		for(int s:data1.reverse())
			System.out.print(s+" ");
		System.out.println();
		for(int s:data1.random())
			System.out.print(s+" ");
		System.out.println();
	}

}
